package ictbk.ttmk51.grapro.app.safephonebook;

import ictbk.ttmk51.grapro.app.LoginActivity;
import ictbk.ttmk51.grapro.app.R;
import ictbk.ttmk51.grapro.app.common.MyActivity;
import ictbk.ttmk51.grapro.app.service.GetWebservice;
import ictbk.ttmk51.grapro.app.utils.ContactProvider;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class RestoreContactActivity extends MyActivity {
	private ArrayList<BackupInfo>		items				= new ArrayList<BackupInfo>();
	private ListView					lv;
	private ArrayAdapter<BackupInfo>	aa;
	ContactProvider						contactAPI;
	private String						messageEmptyList	= "Don't have any backup verions";
	Handler								myHandler			= new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("Restore Contacts");
		setContentView(R.layout.restore_screen);
		try {

			contactAPI = new ContactProvider();
			contactAPI.setCr(getContentResolver());
			contactAPI.setCur(getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));
			items = GetWebservice.getAllBackupInfo(LoginActivity.getUserID());

		} catch (Exception e) {
			new AlertDialog.Builder(this).setMessage(e.getMessage()).show();
		}
		Log.i("abc dắt dê đi....", "heeeeeee..........");
		System.out.print(items.size());
		lv = (ListView) findViewById(R.id.List);
		aa = new ArrayAdapter<BackupInfo>(this, R.layout.item_backup_info, items) {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View v = convertView;
				if (v == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					v = vi.inflate(R.layout.item_backup_info, null);
				}

				TextView tvDate = (TextView) v.findViewById(R.id.tvDate);
				tvDate.setText(items.get(position).getDate());
				TextView tvTime = (TextView) v.findViewById(R.id.tvTime);
				tvTime.setText(items.get(position).getTime());
				TextView tvNote = (TextView) v.findViewById(R.id.tvNote);

				tvNote.setText("Notes: " + items.get(position).getNotes());
				CheckBox chkSelectBackupVersion = (CheckBox) v.findViewById(R.id.chkSelectBackupVersion);
				chkSelectBackupVersion.setChecked(items.get(position).isChecked());

				return v;
			}
		};
		Log.i("Số lượng items", String.valueOf(items.size()));
		if (items.size() == 0) {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText(messageEmptyList);
		} else {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
		}
		lv.setAdapter(aa);
	}

	int	numberOfItemSelected	= 0;

	public void checkItemClick(View v) {
		int index = lv.getPositionForView(v);
		items.get(index).setChecked(((CheckBox) v).isChecked());
		numberOfItemSelected += ((CheckBox) v).isChecked() ? 1 : -1;
	}

	public void deleteBackupVersion(View v) {
		if (items.isEmpty()) {
			showToast("Don't have any vesions to delete");
			return;
		}
		boolean hasCheck = false;
		for (BackupInfo bki : items) {
			if (bki.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			showConfirmDialog("Delete Confirm", "Are you sure you want to delete?", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					try {
						for (int i = 0; i < items.size(); i++) {
							if (items.get(i).isChecked()) {
								if (GetWebservice.deleteBackupVersion(items.get(i).getVersionID())) {
									items.remove(i--);
									numberOfItemSelected--;
								} else {
									showToast("Error while attempting to delete on server");
								}
							}
						}
						aa.notifyDataSetChanged();
						if (items.size() == 0) {
							((TextView) findViewById(R.id.tvMessageEmptyList)).setText(messageEmptyList);
						}
					} catch (Exception e) {
						new AlertDialog.Builder(RestoreContactActivity.this).setMessage("Exception restore 326: " + e.getMessage()).show();
					}
				}
			});
		} else {
			showToast("Please choose any backup versions");
		}
	}

	public void RestoreButtonClick(View v) {
		if (items.isEmpty()) {
			showToast("Don't have any versions to revert.");
			return;
		}
		if (numberOfItemSelected == 0) {
			showToast("Please choose a version to revert!");
			return;
		}
		if (numberOfItemSelected == 1) {
			new AlertDialog.Builder(this).setTitle("Warning").setIcon(R.drawable.warning).setMessage("All of your current contacts will be delete.\nAre you sure you want to revert?")
				.setPositiveButton("Yes", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						final ProgressDialog pd = showProgressDialog("Reverting...", false);
						new Thread() {
							public void run() {
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										pd.setMessage("Deleting...");
									}
								});
								
								contactAPI.deleteContactToEnd();
								Log.i("Delete Contact", "Done!");
								Log.i("Adding Contact", "..........");
								
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										pd.setMessage("Preparing to revert...");
									}
								});
								for (int i = 0; i < items.size(); i++) {
									BackupInfo info = items.get(i);
									if (info.isChecked()) {
										try {
											// Get all of backup version
											ArrayList<Contact> contacts = GetWebservice.restoreContactList(info.getVersionID());
											Log.i("Version ID", "" + info.getVersionID());
											for (int j = 0; j < contacts.size(); j++) {
												final Contact contact = contacts.remove(j);
												contactAPI.writeContact(contact);
												myHandler.post(new Runnable() {
													@Override
													public void run() {
														pd.setMessage("Reverted: " + contact.getDisplayName());
													}
												});
												
												j--;
											}
											pd.dismiss();
											finish();
										} catch (final Exception e) {
											e.printStackTrace();
											myHandler.post(new Runnable() {
												@Override
												public void run() {
													showErrorDialog("System: " + e.getMessage());
												}
											});											
										}
									}
								}
								

							}
						}.start();
					}
				}).setNegativeButton("No", new OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).show();
		} else {
			showToast("You are only choose a version to revert.");
		}
	}
}